#!/usr/bin/env python
#
#
#    Name: gen_rpiir_config.py
#
#    Description: Generates a basic configuration set of IR codes for your remote
#                 and in return creates a custom config file that will be used as
#                 the overall pulse map set for rpi-ir daemon 
#
#    RPi-IR is a Raspberry Pi IR receiver project using the Sparkfun IR Breakout board + GPIO
#    Copyright (C) 2012  Adam Dosch <adam at wisehippy dot com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################################
# Change    Date        Name            Description
########################################################################################
#  001      07-14-2012  Adam Dosch      Initial Release
#
########################################################################################

from optparse import OptionParser
import ConfigParser
import sys
import os
import re
import datetime
import time

try:
    import RPi.GPIO as GPIO
except ImportError:
    print "Need RPi to continue.  Download from: http://pypi.python.org/pypi/RPi.GPIO"
    sys.exit(1)

Config = ConfigParser.ConfigParser()

###button_pulse_map = {}

sections = {
    "IRsensor": ("pulsetime","maxpulsetime"),
    "GPIO": ("setmode","pin","direction",),
    "buttonmap": ("Power","VolUp","VolDown","ChanUp","ChanDown","DashDot","0","1","2","3","4","5","6","7","8","9","0","Play","Stop","Pause","Record","FF","RW","Mute")
}

def usleep(ms):
    time.sleep(float(ms/1000000))

###def write_header(filehandle):
###    """
###    Writes out header of new ircodes.py file
###    Parameters:
###     - filehandle: file handle object of opened ircodes.py file
###    """
###    
###    filehandle.write("""#!/usr/bin/env python
####
####
#### ircodes.py
####
###""")
###    filehandle.write("# Generated on: " + str(datetime.datetime.now()) + "\n")

def captureIR():
    # Setting initial values
    pulsecollection = []
    
    # Setting pinout map to follow - using Broadcom pin reference
    #if re.match("BCM", Config.get("GPIO", "setmode")):
    #    GPIO.setmode(GPIO.BCM)
    #elif re.match("BOARD", Config.get("GPIO", "setmode")):
    #    GPIO.setmode(GPIO.BOARD)
    #else:
    #    print "Invalid setmode!  Bailing!"
    #    sys.exit(1)
    #    
    # Using BCM GPIO pin 17, set direction to 'input'
    #if re.match("IN", Config.get("GPIO", "direction")):
    #    GPIO.setup(int(Config.get("GPIO", "pin")), GPIO.IN)
    #else:
    #    print "Only set IN for direction!"
    #    sys.exit(1)
    
    #MAXPULSE = Config.get("IRsensor", "maxpulsetime")
    MAXPULSE = 120
    #PULSETIME = Config.get("IRsensor", "pulsetime")
    PULSETIME = 20
    
    GPIO.setmode(GPIO.BCM)
    
    # Using BCM GPIO pin 17, set direction to 'input'
    GPIO.setup(17, GPIO.IN)
    
    while(1):
        # Setting initial values
        currentpulse = 0
        
        while True:
            # Setting initial values
            highpulse = 0
            lowpulse = 0
            
            while GPIO.input(17) == True:
                highpulse = highpulse + 1
                usleep(PULSETIME)
            
                if ((highpulse >= MAXPULSE) and (currentpulse != 0)):                    
                    return currentpulse, pulsecollection

            while GPIO.input(17) == False:
                lowpulse = lowpulse + 1
                usleep(PULSETIME)
                
                if ((lowpulse >= MAXPULSE) and (currentpulse != 0)):
                    return currentpulse, pulsecollection

            if currentpulse == 0:
                pulsecollection.append((0, lowpulse*PULSETIME))
            else:
                pulsecollection.append((highpulse*PULSETIME, lowpulse*PULSETIME))
                
            currentpulse = currentpulse + 1    

def main():
    # Parser setup
    usage = "Usage: %prog -c /path/to/rpiir.conf [-o]"
    
    parser = OptionParser(usage=usage)
    
    parser.add_option("-c", "--config", metavar="/path/to/rpiir.conf", dest="confname", help="Path to create/save rpiir.conf file")
    parser.add_option("-o", "--overwrite", action="store_true", dest="overwrite", default=False, help="Overwrite existing ircodes.py file")
    
    (options, args) = parser.parse_args()
    
    if len(sys.argv)-1 == 0:
        parser.print_help()
        sys.exit(1)

    # If confname option is not set or catch any rogue arguements, bail out!
    if (options.confname is None) or (len(args) > 0):
        parser.error("Invalid parameter or argument specified.  See '--help' for usage.")
    
    # String-ify Uencoded options.confname
    confname = str(options.confname)
    
    ### If path doesn't exist or isn't a directory, bail out!
    ###if not os.path.isdir(pathname):
    ###    parser.error("\n'" + pathname +"' is not a valid directory or does not exist!")
    
    # Does ircodes.py already exist?
    try:
        if os.path.isfile(confname):
            if options.overwrite is False:
                print
                print " Warning: '%s' exists!  Overwrite? " % confname
                answer = raw_input("(y/n): ")
                
                while options.overwrite == False:
                    if re.match("[Y|y]", answer):
                        options.overwrite = True
                    elif re.match("[N|n]", answer):
                        sys.exit(1)
                    else:
                        answer = raw_input("(y/n): ")
        else:
            options.overwrite = True
    except KeyboardInterrupt:
        sys.exit(1)
    
    # Overwrite/Create config file
    f = open(confname, "w")
    
    ###Config = ConfigParser.ConfigParser()
    
    # Build config object
    for k,v in sections.iteritems():

        Config.add_section(k)
        
        for item in v:

            if re.match("buttonmap", k):
                print "Press key on your remote you want associated with the '" + item + "' button: "
                
                (count, pulsemap) = captureIR()
                
                while count != 34:
                    print " -Incorrect pulse count, press your '" + item + "' button again: "
                    (count, pulsemap) = captureIR()
                
                print pulsemap
                    
                Config.set(k,item, pulsemap)
            elif re.match("IRsensor", k):
                value = raw_input(" Set value for '" + item + "' in section '" + k + "': ")
                Config.set(k, item, int(value))                
            else:
                value = raw_input(" Set value for '" + item + "' in section '" + k + "': ")
                Config.set(k, item, value)
    
    # Write out built-configuration
    Config.write(f)
    
    # Closing config file
    f.close()
        
if __name__ == '__main__':
    main()
